<template>
  <view class="recognition-page">
	  <!-- 返回按钮 -->
	  <view class="back-btn" @click="handleBack">
	  	<image class="back-icon" src="/static/mine/right-black.png"></image>
	  </view>
    <!-- 页面标题 -->
    <view class="title-section">
      <text class="main-title">健康照片识别</text>
      <text class="sub-title">通过照片分析您的健康状态</text>
    </view>

    <!-- 图片展示区域 -->
    <view class="image-section">
      <image 
        v-if="imagePath" 
        :src="imagePath" 
        class="preview-image"
		mode="aspectFill"
      ></image>
      <view v-else class="placeholder">
        <text>请选择或拍摄照片</text>
      </view>
    </view>

    <!-- 操作按钮区域 -->
    <view class="button-section">
      <button class="action-button" @click="takePhoto">拍照</button>
      <button class="action-button" @click="chooseImage">上传照片</button>
      <button 
        v-if="imagePath" 
        class="analyze-button" 
        @click="analyzeImage"
      >
        开始分析
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { sendFilePath } from '../../../api/index/camera/camera';
import request from 'vk-uview-ui/libs/request';

// 存储图片路径
const imagePath = ref('');

// 拍照方法
const takePhoto = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['camera'],
    success(res) {
      imagePath.value = res.tempFiles[0].tempFilePath;
    },
    fail(err) {
      console.error('拍照失败:', err);
    }
  });
};

// 选择图片方法
const chooseImage = () => {
  uni.chooseMedia({
    count: 1,
    mediaType: ['image'],
    sourceType: ['album'],//从相册选择
    success(res) {
      imagePath.value = res.tempFiles[0].tempFilePath;
      console.log('选择的图片路径:', imagePath.value);
    },
    fail(err) {
      console.error('选择图片失败:', err);
    }
  });
};

//模拟数据
 const data = {
	 currentstatus:"1.头发稀\n2.肾虚状面容\n3.猜测是程序员。",
	 futurePrediction:"未来可能会出现秃头状况、地中海状况",
	 suggestions:"建议植发"
    };
// 分析图片方法
const baseurl = 'http://192.168.18.111:8080/v1/health';

const analyzeImage = () => {
  if (!imagePath.value) {
    uni.showToast({
      title: '请先选择或拍摄照片',
      icon: 'none'
    });
    return;
  }

  console.log('准备发送的图片路径:', imagePath.value);
  uni.showLoading({ title: '分析中...' });
  //将数据传入后端
  // 使用 uni.uploadFile 上传图片
  uni.uploadFile({
    url: baseurl + '/ai/face_analysis', // 替换为实际的API端点
    filePath: imagePath.value,
    name: 'file',
    header: {
      'Authorization': uni.getStorageSync('token')
    },
    formData: {
      keyWord: 'your-keyword' // 替换为实际需要的关键字
    },
    success: (uploadRes) => {
      try {
        const res = JSON.parse(uploadRes.data);
        if(res.code === 200){
          console.log("返回数据成功", res.data);
          uni.hideLoading();
          uni.showToast({ title: '分析完成', icon: 'success' });
          
          const healthInfo = encodeURIComponent(JSON.stringify(res.data || data));
          uni.navigateTo({
            url: `/components/index/healthDetail/healthDetail?healthInfo=${healthInfo}`
          });
        } else {
          throw new Error(res.msg || '分析失败');
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({ 
          title: error.message || '分析失败，请重试', 
          icon: 'none' 
        });
      }
    },
    fail: (err) => {
      console.error('上传失败:', err);
      uni.hideLoading();
      uni.showToast({ 
        title: '上传失败，请重试', 
        icon: 'none' 
      });
    }
  });
};
// 返回上一页
const handleBack = () => {
	uni.navigateBack();
};

const question = ref('');
const messages = ref([]);
const scrollTop = ref(0);
const isTyping = ref(false);
const typingSpeed = 30; // 更快的打字速度
const aiMsg = ref("");

// 加载历史消息
onMounted(() => {
    const savedMessages = uni.getStorageSync('chatMessages');
    if (savedMessages) {
        messages.value = savedMessages;
        scrollToBottom();
    }
});

const sendQuestion = async () => {
    if (question.value.trim() === '') return;
    
    // 添加用户消息
    const userMessage = { content: question.value, isUser: true };
    messages.value.push(userMessage);
    saveMessages();
    
    // 添加一个临时的AI消息占位
    const aiMessage = { 
        content: '', 
        isUser: false, 
        displayContent: '加载中....' 
    };
    messages.value.push(aiMessage);
    
    // 向后端传数据
    try {
        const data = { keyword: question.value };
        const msg = JSON.stringify(data);
        const res = await putQuestion(msg);
        
        if (res.code === 200) {
            aiMsg.value = res.data;
            // 开始打字机效果
            await typewriterEffect(aiMessage, res.data);
        } else {
            aiMessage.displayContent = '抱歉，我遇到了一些问题';
            saveMessages();
        }
    } catch (err) {
        console.log("传数据失败", err);
        aiMessage.displayContent = '抱歉，网络似乎出现了问题';
        saveMessages();
    }
    
    question.value = '';
    scrollToBottom();
};

// 打字机效果
const typewriterEffect = (message, text) => {
    return new Promise((resolve) => {
        isTyping.value = true;
        message.content = text;
        message.displayContent = '';
        
        let index = 0;
        const timer = setInterval(() => {
            if (index < text.length) {
                message.displayContent += text[index];
                index++;
                scrollToBottom();
            } else {
                clearInterval(timer);
                isTyping.value = false;
                saveMessages();
                resolve();
            }
        }, typingSpeed);
    });
};

const scrollToBottom = () => {
    setTimeout(() => {
        scrollTop.value = Math.random() * 1000000;
    }, 100);
};

const saveMessages = () => {
    uni.setStorageSync('chatMessages', messages.value);
};
</script>

<style scoped >
.recognition-page{
	height: 100vh;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	padding: 60rpx 20rpx;
}
 

.title-section{
  text-align: center;	
}

.main-title{
	font-size: 64rpx;
	color: #2569B7;
	display: block;
}

.sub-title{
	font-size: 32rpx;
	color: #2569B7;
	/* margin-top: 20rpx; */
}
  

.image-section{
	flex: 1;
	max-height: 55%;
	background: rgba(37, 105, 183,0.5);
	border: 4rpx dashed rgba(37, 105, 183,0.8);
	border-radius: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
	overflow: hidden;
  }

.preview-image{
	width: 100%;
	height: 100%;
	object-fit: cover;
	border-radius: 30rpx;
}
  

.placeholder{
	text-align: center;
	color: rgba(255, 255, 255, 0.6);
	font-size: 32rpx;
}
  

.button-section{
	display: flex;
	flex-direction: column;
	gap: 30rpx;
}
  

.action-button, .analyze-button{
	border-radius: 50rpx;
	font-size: 36rpx;
	height: 100rpx;
	line-height: 100rpx;
	width: 100%;
	
}

.action-button{
	background:#2569B7;
	color: white;
	
}
  
.analyze-button{
	background: #2569B7;
	color: white;
}
 /* 返回按钮 */
 .back-btn {
   display: flex;
   align-items: center;
   padding:20rpx 0rpx;
 }
 
 .back-icon {
   width: 60rpx;
   height:60rpx;
 }
</style>